/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-3-16 下午1:41 Created by dwzhang
 */
package com.jade.modules.message.sms.beiyan;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import com.jade.framework.base.JadeSystem;
import com.jade.framework.base.util.DataUtils;
import com.jade.modules.message.sms.*;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * 北燕短信客户端。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a> 
 * @version 1.0 15-3-16 下午1:41
 */
public class BeiyanSmsClient
        extends AbstractSmsClient
{
    protected String url;
    protected String ua;
    protected String pw;
    protected String encoding = "GBK";

    public String getUrl()
    {
        return url;
    }

    public void setUrl(String url)
    {
        this.url = url;
    }

    public String getUa()
    {
        return ua;
    }

    public void setUa(String ua)
    {
        this.ua = ua;
    }

    public String getPw()
    {
        return pw;
    }

    public void setPw(String pw)
    {
        this.pw = pw;
    }

    public String getEncoding()
    {
        return encoding;
    }

    public void setEncoding(String encoding)
    {
        this.encoding = encoding;
    }

    @Override
    public SmsResult send(SmsMessage message, SmsServiceParams params)
    {
//        HttpPost post = new HttpPost(url);
//        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
//        postParams.add(new BasicNameValuePair("ua", ua));
//        postParams.add(new BasicNameValuePair("pw", pw));
//        postParams.add(new BasicNameValuePair("mb", StringUtils.join(message.getTo(), ',')));
//        postParams.add(new BasicNameValuePair("ms", message.getContentString()));
//        //postParams.add(new BasicNameValuePair("ex", "11"));
//        try {
//            post.setEntity(new UrlEncodedFormEntity(postParams, encoding));
//        }
//        catch (Throwable t) {
//            // impossible
//        }

        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        try {
            String url = getUrl() + "?ua=" + ua + "&pw=" + pw + "&mb=" + StringUtils.join(message.getTo(),
                    ',') + "&ms=" + URLEncoder.encode(message.getContentString(), "GBK");
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpclient.execute(httpGet);
            StatusLine statusLine = httpResponse.getStatusLine();
            if (statusLine.getStatusCode() >= 300) {
                return new SmsResult(message.getTo().length, SmsStatus.SC_NETWORK_ERROR, statusLine.toString());
            }
            HttpEntity responseEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(responseEntity);
            EntityUtils.consume(responseEntity);
            //parse sms response
            String[] array = response.split(",");
            int code = DataUtils.getInt(array[0], -99);
            String msgId = array.length > 1 ? array[1] : null;
            int status = SmsStatus.SC_SERVER_ERROR;
            if (code == 0) {
                status = SmsStatus.SC_OK;
            }
            else if (code == -1) {
                status = SmsStatus.SC_NO_AUTH;
            }
            else if (code == -2) {
                status = SmsStatus.SC_NO_RECEIVER;
            }
            else if (code == -3) {
                status = SmsStatus.SC_NO_CONTENT;
            }
            else if (code == -4) {
                status = SmsStatus.SC_LEN_OUTOFBOUND;
            }
            else if (code == -5) {
                status = SmsStatus.SC_TOOMANY_RECEIVER;
            }
            return new SmsResult(message.getTo().length, msgId, status, array[0]);
        }
        catch (Throwable t) {
            return new SmsResult(message.getTo().length, SmsStatus.SC_SERVER_ERROR, t.getMessage());
        }
        finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                }
                catch (Throwable t) {
                    JadeSystem.getLog().warn("Can't colse http response");
                }
            }
        }
    }
}
